<template>
  <ElDialog :title="title" v-model="isOpen" width="60%" append-to-body @closed="handleBeforeClose">
    <avue-form :option="option" v-model="form" ref="listFormRef" @submit="handleSubmit"> </avue-form>
    <template #footer>
      <el-button type="primary" @click="listFormRef.submit()">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import useFormOption from "../combination/useFormOption";
import { addApi, updateApi, getDetailApi } from "@/api/homeSet/messageTypeApi";
import type { IOpenFromDialog } from "@/views/commonType/paramsType";
import { ElMessage } from "element-plus";
import { resetForm } from "@/utils/tool";

const defaultData = {
  imgUrl: "",
};

const emit = defineEmits(["done"]);

const ntype = ref("");
const listFormRef = ref();
const form = ref<any>(defaultData);

const option = useFormOption();

const title = ref("新增");
const isOpen = ref(false);

async function handleSubmit(data: any, done: () => void) {
  try {
    if (ntype.value === "add") {
      await addApi(data);
    }
    if (ntype.value === "edit") {
      await updateApi(data);
    }
    ElMessage.success("操作成功");
    cancel();
    emit("done");
  } catch (err) {}
  done();
}

async function fetchData(id: string) {
  const res = await getDetailApi(id);
  form.value = res.data;
}

async function init(params: IOpenFromDialog) {
  form.value = JSON.parse(JSON.stringify(defaultData));
  isOpen.value = true;
  ntype.value = params.type;

  await nextTick();
  if (params.id) {
    fetchData(params.id);
    title.value = "编辑";
  } else {
    title.value = "新增";
  }
}

function cancel() {
  isOpen.value = false;
}

function handleBeforeClose() {
  resetForm(form, defaultData, listFormRef);
}

defineExpose({
  init,
});
</script>
